<template>
  <div>
    <div class="ul" v-for="item in treeData" :key="item.id">
      <slot :node="item" :data="treeData">
        <div
          class="li"
          :style="{
            paddingLeft: level * 27 + 'px'
          }"
          @click.stop="clickNode(item)"
        >
          <span
            v-if="item.type === 'dir'"
            :class="['icon-triangle', item.isOpen ? 'rotate' : 'rotateFalse']"
          ></span>
          <span>{{ item.name }}</span>
        </div>
      </slot>
      <custom-tree v-show="item.isOpen" :data="item.children" :level="level + 1">
        <template v-slot="{ node, data }">
          <slot :node="node" :data="data">
            <div
              class="li"
              :style="{
                paddingLeft: level * 27 + 'px'
              }"
              @click.stop="clickNode(node)"
            >
              <span
                v-if="item.type === 'dir'"
                :class="[
                  'icon-triangle',
                  item.isOpen ? 'rotate' : 'rotateFalse'
                ]"
              ></span>
              <span>{{ item.name }}</span>
            </div>
          </slot>
        </template>
      </custom-tree>
    </div>
  </div>
</template>
<script>
import customTree from "./tree.vue";
export default {
  name: "custom-tree",
  components: { customTree },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    level: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      treeData: null
    };
  },
  created() {
    this.treeData = this.data;
    this.treeData.forEach((node) => {
      node.level = this.level;
      this.$set(node, "isOpen", true);
    });
  },
  methods: {
    clickNode(node) {
      console.log(node.id)
      node.isOpen = !node.isOpen;
    }
  }
};
</script>
<style scoped>
.li {
  height: 40px;
  line-height: 40px;
  background: #f2f2f2;
  border-bottom: 1px solid #ffffff;
}

.icon-triangle {
  display: inline-block;
  border: 7px solid transparent;
  border-bottom-color: #ccc;
  transform: rotate(90deg);
}
.rotate {
  transform: rotate(180deg);
  transition: all 0.5s;
  position: relative;
  top: 5px;
  right: 5px;
}
.rotateFalse {
  transform: rotate(90deg);
  transition: all 0.2s;
}
</style>
